﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

using SWE4.Data.EmbeddedSensorCloud.DTO.Response;
using EmbeddedSensorCloud.HTTP;
using Newtonsoft.Json;

namespace EmbeddedSensorCloud.Plugin.MicroERP
{
    public class FindInvoicesCommand : ICommand
    {
        #region Fields

        IInvoiceDAO _InvoiceDao;
        JsonSerializerSettings _JsonSettings;

        #endregion

        #region Constructor

        public FindInvoicesCommand(IInvoiceDAO invoiceDao, JsonSerializerSettings jsonSettings)
        {
            this._InvoiceDao = invoiceDao;
            this._JsonSettings = jsonSettings;
        }

        #endregion

        #region ICommand

        public bool CanExecute(Request param)
        {
            return (param.Method.ToUpperInvariant() == "GET" &&
                    Regex.IsMatch(param.Url, @"^/api/invoice[/]?$", RegexOptions.IgnoreCase));
        }

        public ResponseEntity Execute(Request param)
        {
            string customerSearchText = param.Args.GetValueIfKey("customer");
            DateTime? dtMinDate = param.Args.GetValueIfKey("minDate").ParseOrNullDateTime();
            DateTime? dtMaxDate = param.Args.GetValueIfKey("maxDate").ParseOrNullDateTime();
            decimal? dMinSum = param.Args.GetValueIfKey("minSum").ParseOrNullDecimal();
            decimal? dMaxSum = param.Args.GetValueIfKey("maxSum").ParseOrNullDecimal();

            if (string.IsNullOrWhiteSpace(customerSearchText) && dtMinDate == null && dtMaxDate == null && dMinSum == null && dMaxSum == null)
            { throw new BadRequestException(); }

            IEnumerable<InvoiceResponseModel> models = this._InvoiceDao.Read(customerSearchText, dtMinDate, dtMaxDate, dMinSum, dMaxSum);
            string returnString = JsonConvert.SerializeObject(models, this._JsonSettings);

            return new ResponseEntity(Encoding.UTF8.GetBytes(returnString), HttpStatusCode.OK);
        }

        #endregion
    }
}
